// pages/main.js
const {
  $Toast
} = require('../../dist/base/index');
const {
  $Message
} = require('../../dist/base/index');

const HIS_RECORD_KEY = "hisRs";

import {
  getDateWithoutYear,
  getWeek,
  getTimeRan
} from '../../utils/date';

import {
  cal
} from '../../utils/cal';

import {
  formatTime
} from '../../utils/util';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTabIndex: 'cal',

    // 参数

    form: {
      envTemperature: '23',
      envPressure: '101.325',
      param1: '',
      param2: '',
      param3: '',
      param4: '',
      param5: ''
    },
    lastInsertIndex: -1,

    hisRecords: [],

    date: '',
    week: '',
    when: '',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      date: getDateWithoutYear(),
      week: getWeek(),
      when: getTimeRan()
    });
    this.loadHisRecords();
  },



  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  handleCal() {
    wx.showLoading({
      title: '正在计算',
    });
    const res = cal(this.data.form, this.data.lastInsertIndex, false);
    console.log("计算结果：", res);
    if (!res.success) {
      $Toast({
        content: res.msg,
        type: 'warning'
      });
      wx.hideLoading();
      return;
    }
    const otherFormData = res.data;
    const f = {
      ...this.data.form
    };
    const back = {
      ...this.data.form
    };
    const lastIdx = this.data.lastInsertIndex;

    f.param1 = parseFloat(otherFormData.p1).toFixed(2);
    f.param2 = parseFloat(otherFormData.p2).toFixed(2);
    f.param3 = parseFloat(otherFormData.p3).toFixed(2);
    f.param4 = parseFloat(otherFormData.p4).toFixed(2);
    f.param5 = parseFloat(otherFormData.p5).toFixed(2);
    switch (lastIdx) {
      case 0:
        f.param1 = back.param1;
        break;
      case 1:
        f.param2 = back.param2;
        break;
      case 2:
        f.param3 = back.param3;
        break;
      case 3:
        f.param4 = back.param4;
        break;
      case 4:
        f.param5 = back.param5;
        break;
    }
    this.setData({
      form: f
    });
    if (otherFormData.exceed1) {
      $Toast({
        content: '参数错误，压力值应大于等于Pw[中间变量]',
        type: 'warning'
      });
      this.errorReset();
      wx.hideLoading();
      return;
    }
    // if (otherFormData.exceed2) {
    //   $Toast({
    //     content: '露点值大于温度值！',
    //     type: 'warning'
    //   });
    //   this.handleReset();
    //   wx.hideLoading();
    //   return;
    // }

    this.saveCurrentRecord();
    wx.hideLoading();
  },

  handleReset() {
    const f = {
      ...this.data.form
    };
    f.envTemperature = '23';
    f.envPressure = '101.325'
    f.param1 = '';
    f.param2 = '';
    f.param3 = '';
    f.param4 = '';
    f.param5 = '';
    this.setData({
      form: f
    });
  },

  errorReset() {
    const f = {
      ...this.data.form
    };
    f.param1 = '';
    f.param2 = '';
    f.param3 = '';
    f.param4 = '';
    f.param5 = '';
    this.setData({
      form: f
    });
  },

  handleTabIndexChanged({
    detail
  }) {
    this.setData({
      currentTabIndex: detail.key
    });
    console.log(this.data.currentTabIndex);
  },


  /**
   * 加载历史记录
   */
  loadHisRecords() {
    const his = wx.getStorageSync(HIS_RECORD_KEY);
    console.log(his);
    this.setData({
      hisRecords: his
    });
  },

  /**
   * 保存当前记录
   */
  saveCurrentRecord() {
    let records;
    if (!this.data.hisRecords) {
      records = [];
    } else {
      records = this.data.hisRecords;
    }
    const storeageRec = {
      ...this.data.form
    };
    // 增加记录时间
    storeageRec.date = formatTime(new Date());
    // 过滤最长10位长度
    if (storeageRec.envTemperature.length > 10) {
      storeageRec.envTemperature = storeageRec.envTemperature.substr(0, 10);
    }
    if (storeageRec.envPressure.length > 10) {
      storeageRec.envPressure = storeageRec.envPressure.substr(0, 10);
    }
    if (storeageRec.param1.length > 10) {
      storeageRec.param1 = storeageRec.param1.substr(0, 10);
    }
    if (storeageRec.param2.length > 10) {
      storeageRec.param2 = storeageRec.param2.substr(0, 10);
    }
    if (storeageRec.param3.length > 10) {
      storeageRec.param3 = storeageRec.param3.substr(0, 10);
    }
    if (storeageRec.param4.length > 10) {
      storeageRec.param4 = storeageRec.param4.substr(0, 10);
    }
    if (storeageRec.param5.length > 10) {
      storeageRec.param5 = storeageRec.param5.substr(0, 10);
    }


    console.log("存储：", storeageRec);
    records.splice(0, 0, storeageRec);

    this.setData({
      hisRecords: records
    });
    this.removeStorageRecords();
    // 最大只保存100条记录
    if (records.length >= 99) {
      this.removeStorageRecords();
    } else {
      wx.setStorageSync(HIS_RECORD_KEY, records);
    }
  },

  /**
   * 清空历史记录
   */
  clearHisRecords() {
    this.setData({
      hisRecords: []
    });

    this.removeStorageRecords();
    $Message({
      content: '清除成功',
      type: 'success'
    });
  },

  removeStorageRecords() {
    try {
      wx.removeStorageSync(HIS_RECORD_KEY);
      wx.clearStorageSync();
    } catch (e) {
      $Toast({
        content: '清除失败',
        type: 'error'
      });
    }
  },

  // 温度文本框改变值
  change1: function (e) {
    let value = 'form.envTemperature';
    this.setData({
      [value]: e.detail.detail.value,
    });
    this.resetOtherParamValue();
  },

  // 压力文本框改变值
  change2: function (e) {
    let value = 'form.envPressure';

    if (e.detail.detail.value == '') {
      this.resetEmptyValue();
      return;
    }

    if (!this.checkPositiveNumberBy3(e)) {
      $Toast({
        content: '压力数值必须大于0，且小数位数不超三位',
        type: 'error'
      });
      this.resetValue(value);
      return;
    }

    this.setData({
      [value]: e.detail.detail.value
    });
    this.resetOtherParamValue();
  },

  // 相对湿度输入框
  change3: function (e) {
    let value = 'form.param1';

    if (e.detail.detail.value == '') {
      this.resetEmptyValue();
      return;
    }

    if (!this.checkPositiveNumber(e)) {
      $Toast({
        content: '相对湿度数值范围0-100，且小数位数不超两位',
        type: 'error'
      });
      this.resetValue(value);
      return;
    }
    const number = e.detail.detail.value;
    if (number < 0 || number > 100) {
      $Toast({
        content: '相对湿度值超出范围[0, 100]',
        type: 'warning'
      });
    }
    this.setData({
      [value]: e.detail.detail.value,
      lastInsertIndex: 0
    });
    const res = cal(this.data.form, this.data.lastInsertIndex, true);
    if (!res.success) {
      $Toast({
        content: res.msg,
        type: 'error'
      });
      this.setData({
        [value]: '',
        lastInsertIndex: 0
      });
    }
  },

  // 露点输入框
  change4: function (e) {
    let value = 'form.param2';
    
    if (e.detail.detail.value == '') {
      this.resetEmptyValue();
      return;
    }

    if (e.detail.detail.value == '-'){
      return;
    }

    if (!this.checkRealNumber(e)) {
      $Toast({
        content: '请输入实数，最多两位小数',
        type: 'error'
      });
      this.resetValue(value);
      return;
    }
    const number = e.detail.detail.value;
    if (number > parseFloat(this.data.form.envTemperature)) {
      $Toast({
        content: '露点值应小于等于温度值',
        type: 'warning'
      });
    }
    this.setData({
      [value]: e.detail.detail.value,
      lastInsertIndex: 1
    });
    const res = cal(this.data.form, this.data.lastInsertIndex, true);
    if (!res.success) {
      $Toast({
        content: res.msg,
        type: 'error'
      });
      this.setData({
        [value]: '',
        lastInsertIndex: 1
      });
    }
  },

  // 体积百分比（干）输入框
  change5: function (e) {
    let value = 'form.param3';

    if (e.detail.detail.value == '') {
      this.resetEmptyValue();
      return;
    }

    if (!this.checkPositiveNumber(e)) {
      $Toast({
        content: '体积百分比(干)取值正数，且小数位数不超两位',
        type: 'error'
      });
      this.resetValue(value);
      return;
    }

    this.setData({
      [value]: e.detail.detail.value,
      lastInsertIndex: 2
    });
    const res = cal(this.data.form, this.data.lastInsertIndex, true);
    if (!res.success) {
      $Toast({
        content: res.msg,
        type: 'error'
      });
      this.setData({
        [value]: '',
        lastInsertIndex: 2
      });
    }
  },

  // 体积百分比（湿）输入框
  change6: function (e) {
    let value = 'form.param4';

    if (e.detail.detail.value == '') {
      this.resetEmptyValue();
      return;
    }

    if (!this.checkPositiveNumber(e)) {
      $Toast({
        content: '体积百分比(湿)取值正数，且小数位数不超两位',
        type: 'error'
      });
      this.resetValue(value);
      return;
    }
    this.setData({
      [value]: e.detail.detail.value,
      lastInsertIndex: 3
    });

    const res = cal(this.data.form, this.data.lastInsertIndex, true);
    if (!res.success) {
      $Toast({
        content: res.msg,
        type: 'error'
      });
      this.setData({
        [value]: '',
        lastInsertIndex: 3
      });
    }
  },

  // 绝对湿度输入框
  change7: function (e) {
    let value = 'form.param5';

    if (e.detail.detail.value == '') {
      this.resetEmptyValue();
      return;
    }

    if (!this.checkPositiveNumber(e)) {
      $Toast({
        content: '绝对湿度取值正数，且小数位数不超两位',
        type: 'error'
      });
      this.resetValue(value);
      return;
    }
    this.setData({
      [value]: e.detail.detail.value,
      lastInsertIndex: 4
    });
    const res = cal(this.data.form, this.data.lastInsertIndex, true);
    if (!res.success) {
      $Toast({
        content: res.msg,
        type: 'error'
      });
      this.setData({
        [value]: '',
        lastInsertIndex: 4
      });
    }
  },

  focus1: function (e) {
    this.setData({
      ['form.param2']: '',
      ['form.param3']: '',
      ['form.param4']: '',
      ['form.param5']: '',
      lastInsertIndex: 0
    });
  },

  focus2: function (e) {
    this.setData({
      ['form.param1']: '',
      ['form.param3']: '',
      ['form.param4']: '',
      ['form.param5']: '',
      lastInsertIndex: 1
    });
  },

  focus3: function (e) {
    this.setData({
      ['form.param1']: '',
      ['form.param2']: '',
      ['form.param4']: '',
      ['form.param5']: '',
      lastInsertIndex: 2
    });
  },

  focus4: function (e) {
    this.setData({
      ['form.param1']: '',
      ['form.param2']: '',
      ['form.param3']: '',
      ['form.param5']: '',
      lastInsertIndex: 3
    });
  },

  focus5: function (e) {
    this.setData({
      ['form.param1']: '',
      ['form.param2']: '',
      ['form.param3']: '',
      ['form.param4']: '',
      lastInsertIndex: 4
    });
  },

  checkRealNumber(e) {
    return this.checkIsRealNumber(e.detail.detail.value);
  },

  checkPositiveNumber(e) {
    return this.checkIsPositiveNumber(e.detail.detail.value);
  },

  checkPositiveNumberBy3(e) {
    return this.checkIsPositiveNumberBy3(e.detail.detail.value);
  },

  checkNumber(e) {
    return this.checkIsNumber(e.detail.detail.value);
  },

  checkIsRealNumber(valueStr) {
    const regex = /^([\+ \-]?(([1-9]\d*)|(0)))([.]\d{0,2})?$/;
    if (valueStr!= "") {
      if (!regex.test(valueStr)) {
        return false;
      }
    }
    return true;
  },

  checkIsPositiveNumber(valueStr) {
    const regex = /^((([1-9]\d*)|(0)))([.]\d{0,2})?$/;
    if (valueStr!= "") {
      if (!regex.test(valueStr)) {
        return false;
      }
    }
    return true;
  },

  checkIsPositiveNumberBy3(valueStr) {
    const regex = /^((([1-9]\d*)|(0)))([.]\d{0,3})?$/;
    if (valueStr!= "") {
      if (!regex.test(valueStr)) {
        return false;
      }
    }
    return true;
  },

  checkIsNumber(valueStr) {
    // return !isNaN(parseFloat(valueStr));
    const re = /^[+-]?((\d*[.](\d{0,})$)|(\d+$))/;
    if (valueStr != "") {
      if (!re.test(valueStr)) {
        return false;
      }
    }
    return true;
  },

  resetValue(value) {
    this.setData({
      [value]: ''
    });
  },
  resetOtherParamValue() {
    this.setData({
      ['form.param1']: '',
      ['form.param2']: '',
      ['form.param3']: '',
      ['form.param4']: '',
      ['form.param5']: '',
    });
  },

  resetEmptyValue() {
    this.setData({
      ['form.param1']: '',
      ['form.param2']: '',
      ['form.param3']: '',
      ['form.param4']: '',
      ['form.param5']: '',
      lastInsertIndex: -1
    });
  }
})